package com.heng.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
//自旋锁，轻量级加锁
public class SpinLockDemo3 {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();
    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"\t---come in");

        while (!atomicReference.compareAndSet(null, thread)) {
        }
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"\t---task over");
    }

    public static void main(String[] args) {
        SpinLockDemo3 spinLockDemo3 = new SpinLockDemo3();
        new Thread(() ->{
            spinLockDemo3.lock();
            try {TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}
            spinLockDemo3.unlock();
        },"a").start();

        try {TimeUnit.SECONDS.sleep(5);}catch (InterruptedException e) {e.printStackTrace();}
        new Thread(() ->{
            spinLockDemo3.lock();
            spinLockDemo3.unlock();
        },"b").start();
    }
}
